#include "radiospy.h"
#include <cstdlib>

int main() {
	
	FILE *mic;
	FILE *thr;
	char data[2];
	int val;
	int thresh;
	void *bufp;
	bufp=data;
	
	if (!(mic=fopen(dsp_to_use,"rb"))) {
		printf("Error Could not open Sound device.\n");
		exit(0);
	}
	
	printf("MICTUNE v0.1 for RadioSpy\n");
	printf("Coded by Jonathan Endersby\n");
	printf("Based on original work by Richard Svensson\n");
	printf("This software is GPL\n\n");
	
	
	printf("This will calibrate the threshold for the\n");
	printf("curent microphone level.\n");
	printf("Please be as quiet as you can. But make sure\n");
	printf("the microphone is ON.\n");
	printf("Please wait..\n");
		
	val = 125;
	thresh = 125;
		
	for (int i=0;i<=50000;i++) {
		data[0]=' ';
		data[1]=' ';
		fread(bufp,1,1,mic);	
		val = abs((int)data[0]);	
		if (val<thresh) {
			thresh=val; 
			printf("Threshold lowered to %d\n", thresh);
		}
	}

	fclose(mic);

	printf("Calibration complete - Calculated threshold as %d, Setting at %d\n",  thresh, thresh-5);

	thresh = thresh - 5;
	
	if (!(thr=fopen("threshold.bin","w"))) {
		printf("Error could not open threshold.bin\n");
		printf("Make sure that radiospy is not running\n");
		exit(0);
	}
	

	
	bufp=&thresh;
	fwrite(bufp,1,1,thr);
	fclose(thr);
}
